package com.example.captcha.Controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.captcha.model.Captcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {

    @Autowired
    private Captcha captcha;
    private static final long session_valid_timeout = 60 * 1000;

    @RequestMapping("/get")
    public void get(HttpServletResponse response, HttpSession session){

        try {
            //定义图形验证码的长和宽
            LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captcha.getWidth(), captcha.getHeight());
            //存储session
            session.setAttribute(captcha.getSession().getKey(), lineCaptcha.getCode());
            session.setAttribute(captcha.getSession().getDate(), new Date());
            //图形验证码写出，可以写出到文件，也可以写出到流
            lineCaptcha.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

   @RequestMapping("/check")
    public Boolean check(String inputCode, HttpSession session){
        //校验
       if(!StringUtils.hasLength(inputCode)){
           return false;
       }
       String key = (String)session.getAttribute(captcha.getSession().getKey());
       Date saveDate = (Date) session.getAttribute(captcha.getSession().getDate());
       //比较
       if(inputCode.equals(key)){
           //验证码是否过期
           if(saveDate != null && System.currentTimeMillis() - saveDate.getTime() < session_valid_timeout)
               return true;
       }
       return false;
    }
}
